import React, { useState } from 'react';
import BreadCrumb from '@/components/BreadCrumb';
import s from './style.module.less';
import { datetime } from '@/common/formatter';

import { Table, Loading } from '@knownsec/react-component';
import { useLocation, useHistory } from 'react-router-dom';
import {
  securityNameMap,
  seoDetailColumns,
  privacyDetailColumns,
  miningDetailColumns,
  sensDetailColumns,
  maDetailColumns,
} from '../ScanRes/columns';
import downloadIcon from '@/assets/svg/download.svg';
import { GetQueryString } from '@/common/constant';
import { getGroupResult } from '~/API';
import cn from 'classnames';
import Compare from './compare';
import EmptyData from '@/components/EmptyData';

export default function dashboard() {
  const search = useLocation().search;
  const id = GetQueryString(search, 'id');
  const tid = GetQueryString(search, 'tid');
  const type = GetQueryString(search, 'type');
  const sid = GetQueryString(search, 'sid');
  const rowSid = GetQueryString(search, 'rowSid');
  const backparam = GetQueryString(search, 'back');

  const [arr, setBread] = useState([]);
  const [title, setTitle] = useState('');
  const [columns, setColumns] = useState([]);
  const [data, setData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [atype, setType] = useState('');
  const [loading, setLoading] = useState(true);
  const [isEmpty, setIsEmpty] = React.useState(null);

  const initData = (data) => {
    const t = data.event_name ? securityNameMap[data.event_name] : '';
    setTitle(t);
    let breadArr = [
      { link: '/', name: '监测列表' },
      {
        link: {
          pathname: '/dashboard/',
          search: `id=${tid}&filter=${encodeURI(backparam)}`,
        },
        name: '结果详情',
      },
      { link: '', name: t + '详情', active: true },
    ];
    if (sid && sid !== 'undefined' && sid !== 'null') {
      breadArr = [
        { link: '/', name: '监测列表' },
        {
          link: {
            pathname: '/dashboard/',
            search: `id=${tid}&sid=${sid}&type=${type}&filter=${encodeURI(backparam)}`,
          },
          name: '结果详情',
        },
        { link: '', name: t + '详情', active: true },
      ];
    }

    setBread(breadArr);
    setType(data.event_name);
    setData(data);
    codeDetails(data);

    let columns = [];
    // 1: '暗链',2: '挂马',3: '挖矿',4: 'SEO劫持',5: '敏感词',6: '隐私信息',7: '坏链',8: '变更信息',
    if (data.event_name) {
      switch (data.event_name) {
        case 'malscan':
          columns = maDetailColumns;
          setTableData(data?.detail?.results);
          break;
        case 'cryptojacking':
          columns = miningDetailColumns;
          setTableData(data?.detail?.results);
          break;
        case 'seo_hijack':
          columns = seoDetailColumns;
          setTableData(data?.detail?.details);
          break;
        case 'keyword':
          columns = sensDetailColumns;
          setTableData(data?.detail?.results);
          break;
        case 'privacy_disclosure':
          columns = privacyDetailColumns;
          setTableData(data?.detail?.results);
          break;
        default:
          columns = [];
          break;
      }
      setColumns(columns);
    }
  };
  const getData = () => {
    setLoading(true);
    if (id && rowSid) {
      getGroupResult({ id: rowSid, data: { event_id: id } }).then((res) => {
        if (res.status === 'success') {
          initData(res.data?.data.events[0] || {});
        }
        setLoading(false);
      });
    } else {
      return Message.show({
        pro: true,
        type: 'error',
        message: '信息缺失',
        showClose: false,
      });
    }
  };

  const codeDetails = (data) => {
    const empty = <EmptyData />;
    const style = {
      background: '#fff9ee',
      borderWidth: '1px',
      borderStyle: 'solid',
      borderColor: '#fee8b6',
    };
    let str = '';
    const dom = [];
    const rs = data?.detail?.results || [];
    let matchKey = 'url';
    if (data.event_name) {
      switch (data.event_name) {
        case 'malscan':
          matchKey = 'url';
          break;
        case 'cryptojacking':
          matchKey = 'src';
          break;
        case 'seo_hijack':
          matchKey = 'description';
          break;
        case 'keyword':
          matchKey = 'word';
          break;
        case 'privacy_disclosure':
          matchKey = 'content';
          break;
        default:
          matchKey = '';
          break;
      }
    }
    if (!rs.length) {
      setIsEmpty(null);
    }
    rs.forEach((val) => {
      if (!val.evidences?.length) {
        return false;
      }
      val.evidences.forEach((code) => {
        str = code.split(val[matchKey]);
        dom.push(
          <p className={s.codeRow}>
            {str.map((e, i) => {
              if (i < str.length - 1) {
                return (
                  <>
                    <span>{e}</span>
                    <span style={style}>{val[matchKey]}</span>
                  </>
                );
              } else {
                return (
                  <>
                    <span>{e}</span>
                    <p>......</p>
                  </>
                );
              }
            })}
          </p>
        );
      });
    });

    if (dom[0]) {
      setIsEmpty(
        <div>
          {dom.map((e) => {
            return e;
          })}
        </div>
      );
    } else {
      setIsEmpty(null);
    }
  };

  React.useMemo(() => {
    getData();
  }, [id]);
  return (
    <>
      <BreadCrumb arr={arr} />
      <div className={s.securityinfo}>
        <Loading show={loading} />
        <div className={s.title}>{title}</div>
        <div className={s.itemwrap}>
          <div className={s.subtitle}>风险地址</div>
          <div className={cn(s.item, s.redstyle)}>
            <p>{data?.detail?.url || '-'}</p>
          </div>
        </div>
        {atype == 'black_links' || atype == 'broken_links' ? (
          <div className={s.itemwrap}>
            <div className={s.subtitle}>{title}接</div>
            <div className={cn(s.item, s.maxh)}>
              {atype == 'black_links'
                ? data?.detail?.links?.map((l) => {
                    return <p>{l}</p>;
                  })
                : data?.detail?.results?.map((l) => {
                    return <p>{l.url}</p>;
                  })}
            </div>
          </div>
        ) : null}

        {columns.length ? (
          <div className={s.itemwrap}>
            <div className={s.subtitle}>详细信息</div>
            <Table
              className={s.maxtable}
              columns={columns}
              tableLoading={loading}
              loadingLabel=""
              data={tableData}
            ></Table>
          </div>
        ) : null}
        {atype && atype == 8 ? <Compare /> : null}
        {atype && atype != 8 && atype != 'malscan' && atype != 'broken_links' ? (
          <div className={s.itemwrap}>
            <div className={s.subtitle}>
              风险地址源码
              <p>
                抓取时间：{data.updated_at && isEmpty ? datetime(data.updated_at) || '--' : '--'}
              </p>
              {/* <span>
                <img src={downloadIcon} alt="" />
                下载取证信息
              </span> */}
            </div>
            <div className={s.item}>{isEmpty || <EmptyData />}</div>
          </div>
        ) : null}
      </div>
    </>
  );
}
